<template>
  <button
    :class="[buttonType]"
    :disabled="disabled"
    :style="{width,height,borderRadius,background}"
    :open-type="openType"
    :data-im-id="imId"
    class="button flex-row flex-center"
    @click.stop="buttonClick"
    @contact="handleContact"
    @addshortcut="handleAddShortcut"
  >
    <slot name="leading" />
    <slot>
      <text class="text-26 color-white" :style="{fontSize, color: fontColor}" :class="{'text-bold':bold}">{{ text }}</text>
    </slot>
  </button>
</template>

<script setup lang="ts">
import useUserStore from '@/store/user'
import { jump, toast } from '@/common/util'

const userStore = useUserStore()

interface IProps{
  text?: string
  width?: string
  background?: string
  height?: string
  radius?: string
  fontSize?: string
  fontColor?: string
  openType?: string
  imId?: string
  tno?: string
  round: boolean
  bold: boolean
  pain: boolean
  type: string
  disabled: boolean
  checkLogin: boolean
}

const props = withDefaults(defineProps<IProps>(), {
  bold: false,
  pain: false,
  disabled: false,
  round: true,
  checkLogin: false,
  type: 'primary'
})

const buttonType = computed(() => {
  if (props.pain) return 'button-pain-' + props.type
  else return 'button-' + props.type
})

const borderRadius = computed(() => {
  if (props.round) return props.height ? parseInt(props.height) / 2 + 'rpx' : ''
  else return props.radius || ''
})

const $emit = defineEmits(['click', 'contact', 'aadShortcut'])

function debounce(fn:()=>void, wait = 300) {
  let canClick = true
  let timeout:number = 0
  return function() {
    if (canClick) {
      fn()
      canClick = false
    }
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      canClick = true
    }, wait)
  }
}

function handleClick() {
  if (props.checkLogin && !userStore.token) {
    jump('login')
    toast('请先登录')
    return
  }
  $emit('click')
}

const buttonClick = debounce(handleClick)

function handleContact(e: any) {
  $emit('contact', e)
}

function handleAddShortcut(e: any) {
  $emit('aadShortcut', e)
}
</script>

<style scoped lang="scss">
.button{
  width: 100%;
  height: 60rpx;
  border-radius: 30rpx;
  background:none;
  padding: 0;
  margin: 0;

  &.button-primary{
    background: $color-primary;
  }

  &.button-pain-primary{
    border:2rpx solid $color-primary;

    .color-white{
      color: $color-primary;
    }

  }

  &.button-gray{
    background: $color-border;

    .color-white{
      color: $color-grey;
    }

  }

  &.button-pain-gray{
    border:2rpx solid #D3D3D3;

    .color-white{
      color: $color-t2;
    }

  }

  &.button-white{
    background: $color-white;

    .color-white{
      color: #FFA800;
    }

  }

  &:after{
    display: none;
  }

}
</style>
